<template>
  <div class="page-editor editor-wrapper" v-loading="loading" v-if="isShow">
    <!--左侧导航-->
<!--    <div class="editor-side-bar border-R">-->
<!--      <el-tabs tab-position="left" v-model="activeSideBar" style="height: 100%;">-->
<!--        <template v-for="(item, index) in sidebarMenus">-->
<!--          <el-tab-pane :name="item.value"  :key="index" v-if="!item.pageMode || (item.pageMode && item.pageMode === pageMode)">-->
<!--            <el-tooltip slot="label" class="item" effect="dark" :content="item.label" placement="right">-->
<!--              <i :class="item.elementUiIcon"></i>-->
<!--            </el-tooltip>-->
<!--          </el-tab-pane>-->
<!--        </template>-->
<!--      </el-tabs>-->
<!--    </div>-->
    <!--组件&页面&模板-->
    <div class="editor-page-edit-wrapper">
      <componentLibs v-if="activeSideBar === 'componentLibs'" :componentsList="componentsList"/>
      <templateLibs v-if="activeSideBar === 'templateLibs'"/>
    </div>
    <!--页面编辑区域-->
    <div class="editor-main">
      <div class="control-bar-wrapper">
        <controlBar
                :scale.sync="canvasConfig.scale"
                showType="store"
                @showPreview="showPreviewFn"
                @cancel="cancelFn"
                @publish="publishFn"
                @save="saveFn"/>
      </div>
      <editorPan :scale.sync="canvasConfig.scale" :store="store"/>
    </div>
    <!--属性编辑区域-->
    <div class="el-attr-edit-wrapper scrollbar-wrapper">
      <el-tabs v-model="activeAttr" stretch>
        <el-tab-pane label="属性" name="属性">
          <attrEdit></attrEdit>
        </el-tab-pane>
<!--        <el-tab-pane label="页面设置" name="页面属性">-->
<!--          <pageAttrEdit></pageAttrEdit>-->
<!--        </el-tab-pane>-->
      </el-tabs>
    </div>
    <!--预览-->
    <previewPage
            v-if="showPreview"
            :pageData="projectData"
            :pageId="id"
            @closePreview="showPreview = false"
            @publishFn="publishFn"
            @saveFn="saveFn"></previewPage>
    <!--我的图片-->
  </div>
</template>

<script>
	import componentLibs from '../components/component-libs/Index'
	import templateLibs from '../components/template-libs'
	import editorPan from '../components/editor-panel/Index'
    import eleConfig from './ele-config'
	// 属性编辑相关组件
	import attrEdit from '../components/attr-configure/attr-edit'
	import pageAttrEdit from '../components/attr-configure/page-attr-edit'

	import controlBar from '../components/control-bar'

	import previewPage from '../components/preview'

	import {mapState, mapGetters} from 'vuex'
	import html2canvas from 'html2canvas'

    import {
      update,
      getDetail,
      storeDetailInfo,
      editStoreItem
    } from "@/api/cms/seller/pageInfo";
	export default {
		components: {
			componentLibs,
			templateLibs,
			editorPan,
			attrEdit,
			pageAttrEdit,
			controlBar,
			previewPage
		},
		data() {
			return {
              isShow:true,
              upBannerData:[],
              componentsList: eleConfig,
              id: '', // 当前页面id
              loading: false,
              showPreview: false,
              activeAttr: '属性',
              activeSideBar: 'componentLibs',
              sidebarMenus: [
                {
                  label: '组件列表',
                  value: 'componentLibs',
                  elementUiIcon: 'el-icon-s-operation'
                },
                {
                  label: '模板库',
                  value: 'templateLibs',
                  elementUiIcon: 'el-icon-files'
                }
              ],
              canvasConfig: {
                scale: 1
              },
              store:{},
              storeDetailInfo:{},
			}
		},
		computed: {
			...mapState({
				projectData: state => state.editor.projectData,
			}),
			...mapGetters([
				'pageMode'
			])
		},
		created() {
			this.$store.dispatch('setPrjectData')
			this.id = this.$route.query.id;
			this.storeId=this.$route.query.storeId;
			this.initPageData();
		},
		methods: {
            //reload
          reload(){
            this.isShow=false
            this.$nextTick(()=>{
              this.isShow=true
            })
          },
			/**
			 * 初始化页面数据
			 */
			initPageData() {
              var jsonstr = {
                "coverImage":"",
                "pageMode":"h5",
                "width":375,
                "height":644,
                "elements":[],
                "commonStyle":{
                  "backgroundColor":"",
                  "backgroundImage":"",
                  "backgroundSize":"cover"
                }
              };
              getDetail(this.id).then(res=>{
                if(res.data.data.layoutJson){
                  jsonstr = JSON.parse(res.data.data.layoutJson);
                  if(jsonstr.elements.length!=0){
                    jsonstr.elements.forEach(item=>{
                      if(item.elName=='qk-store-banner'){
                        localStorage.setItem("bannerData",JSON.stringify(item.propsValue.prop.arr))
                      }
                    })
                  }
                }
                this.$store.dispatch('setPrjectData', {
                  ...jsonstr
                });
                storeDetailInfo(this.storeId).then(r=>{
                    this.store=r.data.data.store;
                    this.storeDetailInfo=r.data.data.StoreDetailInfo;
                })
              });
			},
			/**
			 * 保存
			 */
			async saveFn() {
              if(this.projectData.elements.length!=0){
                let num=0
                this.projectData.elements.forEach(item=>{
                  if(item.elName=='qk-store-banner'){
                    this.upBannerData=item.propsValue.prop.arr
                    num++;
                  }
                })
                if(num>1){
                  this.$message({
                    type: 'error',
                    message: '店招轮播只能设置1个'
                  });
                  return  false
                }
              }
              let Flag=false
              // 判断两次banner的数组长度
                let bannerData=JSON.parse(localStorage.getItem("bannerData"))
                if(this.upBannerData.length!=bannerData.length){
                  Flag=true
                }else{
                  bannerData.forEach((item,index)=>{
                    if(item.imgUrl!=this.upBannerData[index].imgUrl){
                      Flag=true
                    }
                  })
                }
              if(Flag){
                this.$confirm('店内banner轮播有修改需后台审核, 是否继续?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  editStoreItem(this.storeId,1).then(res=>{
                    if(res.data.code==200){
                      this.$message({
                        type: 'info',
                        message: '保存成功'
                      });
                      this.updata()
                      this.$router.go(0)
                    }
                  })
                }).catch(() => {
                  this.$message({
                    type: 'info',
                    message: '已取消修改'
                  });
                  this.$router.go(0)
                });
              }else{
                this.updata()
              }
			},
          updata(){
            // 提交数据再预览
            update({id:this.id,layoutJson:JSON.stringify(this.projectData)}).then(res=>{
              if(res.data.code == 200){
                this.$message({message:"保存成功",type:"primary"});
              }else{
                this.$message({message:res.data.message,type:"primary"});
              }
            })
          },
			/**
			 * 保存
			 */
			async publishFn() {
              update({id:this.id,layoutJson:JSON.stringify(this.projectData)}).then(res=>{
                if(res.data.code == 200){
                  this.$message({message:"保存成功",type:"primary"});
                }else{
                  this.$message({message:res.data.message,type:"primary"});
                }

              })
			},
			async showPreviewFn() {
              update({id:this.id,layoutJsonTemp:JSON.stringify(this.projectData)}).then(res=>{
                if(res.data.code == 200){
                  this.showPreview = true;
                }else{
                  this.$message({message:res.data.message,type:"primary"});
                }
              })
			},
			/**
			 * 退出
			 */
            cancelFn() {
              this.$confirm('确认退出编辑?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.$router.push('/base/store/seller/pageInfoSet')
              }).catch(() => {})
            },
			/**
			 * 提供截屏作为项目主图
			 */
			screenshots() {
				const el = document.querySelector("#canvas-panel")
				return new Promise((resolve, reject) => {
					html2canvas(el).then(canvas => {
						const dataUrl = canvas.toDataURL('image/jpeg', 0.6)
						const blob = this.$mUtils.dataURItoBlob(dataUrl)
						const file = new window.File([blob], +new Date() + '.png', {type: 'image/png'})
						let params = new FormData()
						params.append('file', file);
						this.$axios.post('/common/uploadFile', params).then(res => {
							// 替换主图链接
							this.projectData.coverImage = res.body;
							resolve(res.body)
						}).catch(err => {
							reject(err)
						})
					})
				})
			},

		}
	}
</script>

<style lang="scss" scoped>
  .editor-wrapper {
    display: flex;
    height: 100%;
    position: relative;
    .editor-side-bar {
      width: 55px;
    }
    .editor-page-edit-wrapper {
      width: 210px;
      padding: 0 1px;
    }
    .editor-main {
      flex: 1;
      background: #f0f2f5;
      position: relative;
    }
    .el-attr-edit-wrapper {
      width: 380px;
      padding: 0;
    }
  }

  .control-bar-wrapper {
    /*position: absolute;*/
    /*top: 0px;*/
    /*left: 0;*/
    /*z-index: 1000;*/
    height: 44px;
    width: 100%;
    background: #fff;
    text-align: center;
  }
</style>
<style lang="scss">
  .editor-side-bar {
    .el-tabs__item.is-active {
      background: rgba(37, 165, 137, 0.09);
    }
  }

  .el-attr-edit-wrapper {
    .el-tabs {
      height: 100%;
      padding-left: 16px;
      padding-right: 16px;
      padding-bottom: 10px;
    }
    .el-tabs__content {
      height: calc(100% - 55px);
      & > div {
        height: 100%;
      }
      .attr-edit-inner {
        padding-left: 16px;
        padding-right: 16px;
      }
    }
  }
</style>
